package com.chao.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import com.chao.message.resq.TextMessage;
import com.chao.util.MessageUtil;

/**
 * 核心服务类
 * @author Administrator
 *
 */
public class CoreService {
	 /** 
     * 处理微信发来的请求 
     * @param request 
     * @return 
     */  
    public static String processRequest(HttpServletRequest request) {  
        String respMessage = null;  
        try {  
            // 默认返回的文本消息内容   
            String respContent = "请求处理异常，请稍候尝试！";  
  
            // xml请求解析   
            Map<String, String> requestMap = MessageUtil.parseXml(request);  
  
            // 发送方帐号（open_id）   
            String fromUserName = requestMap.get("FromUserName");  
            // 公众帐号   
            String toUserName = requestMap.get("ToUserName");  
            // 消息类型   
            String msgType = requestMap.get("MsgType");  
  
            // 回复文本消息   
            TextMessage textMessage = new TextMessage();  
            textMessage.setToUserName(fromUserName);  
            textMessage.setFromUserName(toUserName);  
            textMessage.setCreateTime(new Date().getTime());  
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
            textMessage.setFuncFlag(0);  
  
            // 文本消息   
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
//                respContent = "您发送的是文本消息！hello";
            	String contetn = requestMap.get("Content");
                respContent = getTuling(contetn);
            }  
            // 图片消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  
//                respContent = "您发送的是图片消息！photo";
                String picUrl = requestMap.get("PicUrl");
        		FaceService  faces = new FaceService();
        		respContent = faces.detect(picUrl);
            }  
            // 地理位置消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {  
                respContent = "您发送的是地理位置消息！dili";  
            }  
            // 链接消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
                respContent = "您发送的是链接消息！lianjie";  
            }  
            // 音频消息   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
                respContent = "您发送的是音频消息！shengyin";  
            }  
            // 事件推送   
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {  
                // 事件类型   
                String eventType = requestMap.get("Event");  
                // 订阅   
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {  
                    respContent = "谢谢您的关注！guanzhu";  
                }  
                // 取消订阅   
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息   
                	respContent = "您取消了关注！quxiaoguanzhu";
                }  
                // 自定义菜单点击事件   
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
                    // TODO 自定义菜单权没有开放，暂不处理该类消息  
                	// 事件KEY值，与创建自定义菜单时指定的KEY值对应  
                    String eventKey = requestMap.get("EventKey");
                    if (eventKey.equals("11")) {  
                        respContent = "天气预报菜单项被点击！";  
                    } else if (eventKey.equals("12")) {  
                        respContent = "公交查询菜单项被点击！";  
                    } else if (eventKey.equals("13")) {  
                        respContent = "周边搜索菜单项被点击！";  
                    } else if (eventKey.equals("14")) {  
                        respContent = "历史上的今天菜单项被点击！";  
                    } else if (eventKey.equals("21")) {  
                        respContent = "歌曲点播菜单项被点击！";  
                    } else if (eventKey.equals("22")) {  
                        respContent = "经典游戏菜单项被点击！";  
                    } else if (eventKey.equals("23")) {  
                        respContent = "美女电台菜单项被点击！";  
                    } else if (eventKey.equals("24")) {  
                        respContent = "人脸识别菜单项被点击！";  
                    } else if (eventKey.equals("25")) {  
                        respContent = "聊天唠嗑菜单项被点击！";  
                    } else if (eventKey.equals("31")) {  
                        respContent = "Q友圈菜单项被点击！";  
                    } else if (eventKey.equals("32")) {  
                        respContent = "电影排行榜菜单项被点击！";  
                    }
                    else if (eventKey.equals("33")) {  
                        respContent = "幽默笑话菜单项被点击11！";  
                    }
//                    //自定义view事件
//                    else if(eventType.equals(MessageUtil.EVENT_TYPE_VIEW)){
//                    	respContent = "幽默笑话菜单项被点击2！view";
//                    } 
                }
               
                else if(eventType.equals(MessageUtil.EVENT_TYPE_PIC_PhotoOrAlbum)){
                	String eventKey = requestMap.get("EventKey");
                	if(eventKey.equals("35")){
                		String picUrl = requestMap.get("PicUrl");
                		FaceService  faces = new FaceService();
                		respContent = faces.detect(picUrl)+"zhao";
//                		respContent = "拍照被点击！";
                	}
                }
            }  
  
            textMessage.setContent(respContent);  
            respMessage = MessageUtil.textMessageToXml(textMessage);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        return respMessage;  
    }  
    /**
     * 接入图灵机器人
     * @param content
     * @return
     * @throws Exception
     */
    public static String getTuling(String content) throws Exception{
//    	http://simsimi.com/func/req/?lc=ch&msg=你好&ft=0.0
    	JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
    	String TULING_API_URL = "http://www.tuling123.com/openapi/api";
    	String TULING_API_KEY = "25a3a23d36b5363d6005f5a622ebfab9";//图灵的APIKEY
    	String Tuling_url = TULING_API_URL+"?key="+TULING_API_KEY+"&info="+content;
    	URL url = new URL(Tuling_url);
		HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);
		// 设置请求方式（GET/POST）
		httpUrlConn.setRequestMethod("GET");
		
		InputStream inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();
		// 释放资源
		inputStream.close();
		inputStream = null;
		httpUrlConn.disconnect();
		
//		jsonObject = JSONObject.fromObject(buffer.toString());
		
		return buffer.toString();
    }
}
